from rest_framework.authentication import BaseAuthentication
from utils.myjwt import jwttoken
from user import models
import jwt
from rest_framework.exceptions import AuthenticationFailed


class MyAuth(BaseAuthentication):
    def authenticate(self, request):
        tokendata = request.META.get('HTTP_AUTHORIZATION', None)
        # data = jwttoken.check_token(token)
        if tokendata:
            # 分割token
            token = tokendata.split(' ')[1]
            # 解码 拿到用户id去验证
            try:
                data = jwttoken.check_token(token)
                # print(data)
                user = models.User.objects.get(id=data['id'])
                return user, token
            except jwt.ExpiredSignatureError:
                raise AuthenticationFailed('token认证过期')
            except jwt.exceptions.DecodeError:
                raise Exception('token无效')
        else:
            return None, None
